'use client'

import { useState, useEffect } from 'react'
import { Card, Row, Col, Progress, Table, Alert, Button, Tabs, Statistic } from 'antd'
import {
    DashboardOutlined,
    WarningOutlined,
    CheckCircleOutlined,
    ArrowUpOutlined,
    ArrowDownOutlined,
    MinusOutlined
} from '@ant-design/icons'
import { usePerformanceAnalyzer } from '../utils/performanceAnalyzer'
import { useApiCache } from '../utils/apiCache'
import type { PerformanceReport, TrendData } from '../utils/performanceAnalyzer'

const { TabPane } = Tabs

export function PerformanceDashboard() {
    const [latestReport, setLatestReport] = useState<PerformanceReport | null>(null)
    const [isVisible, setIsVisible] = useState(false)
    const { getLatestReport, getReports, getTrend, exportData } = usePerformanceAnalyzer()
    const { getStats: getCacheStats } = useApiCache()

    useEffect(() => {
        const updateReport = () => {
            const report = getLatestReport()
            setLatestReport(report)
        }

        updateReport()
        const interval = setInterval(updateReport, 5000) // 每5秒更新

        return () => clearInterval(interval)
    }, [getLatestReport])

    if (!isVisible) {
        return (
            <Button
                type="primary"
                icon={<DashboardOutlined />}
                onClick={() => setIsVisible(true)}
                style={{
                    position: 'fixed',
                    bottom: 20,
                    right: 20,
                    zIndex: 1000
                }}
            >
                性能监控
            </Button>
        )
    }

    const handleExport = () => {
        const data = exportData()
        const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
        const url = URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.download = `performance-report-${new Date().toISOString()}.json`
        a.click()
        URL.revokeObjectURL(url)
    }

    return (
        <div
            style={{
                position: 'fixed',
                top: 20,
                right: 20,
                width: 800,
                maxHeight: '80vh',
                overflow: 'auto',
                zIndex: 1000,
                backgroundColor: 'white',
                border: '1px solid #d9d9d9',
                borderRadius: 8,
                boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)'
            }}
        >
            <div style={{ padding: 16 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
                    <h3>性能监控仪表板</h3>
                    <div>
                        <Button onClick={handleExport} style={{ marginRight: 8 }}>
                            导出数据
                        </Button>
                        <Button onClick={() => setIsVisible(false)}>
                            关闭
                        </Button>
                    </div>
                </div>

                <Tabs defaultActiveKey="overview">
                    <TabPane tab="概览" key="overview">
                        <OverviewTab report={latestReport} />
                    </TabPane>
                    <TabPane tab="性能指标" key="metrics">
                        <MetricsTab report={latestReport} getTrend={getTrend} />
                    </TabPane>
                    <TabPane tab="缓存状态" key="cache">
                        <CacheTab getCacheStats={getCacheStats} />
                    </TabPane>
                    <TabPane tab="建议" key="recommendations">
                        <RecommendationsTab report={latestReport} />
                    </TabPane>
                </Tabs>
            </div>
        </div>
    )
}

// 概览标签页
function OverviewTab({ report }: { report: PerformanceReport | null }) {
    if (!report) {
        return <Alert message="暂无性能数据" type="info" />
    }

    const getScoreColor = (score: number) => {
        if (score >= 90) return '#52c41a'
        if (score >= 70) return '#faad14'
        return '#ff4d4f'
    }

    const getScoreStatus = (score: number) => {
        if (score >= 90) return 'success'
        if (score >= 70) return 'normal'
        return 'exception'
    }

    return (
        <div>
            <Row gutter={16} style={{ marginBottom: 16 }}>
                <Col span={8}>
                    <Card>
                        <Statistic
                            title="性能得分"
                            value={report.score}
                            precision={1}
                            valueStyle={{ color: getScoreColor(report.score) }}
                            suffix={
                                <Progress
                                    type="circle"
                                    size={60}
                                    percent={report.score}
                                    status={getScoreStatus(report.score)}
                                    showInfo={false}
                                />
                            }
                        />
                    </Card>
                </Col>
                <Col span={8}>
                    <Card>
                        <Statistic
                            title="内存使用率"
                            value={report.memoryUsage?.usedPercent || 0}
                            precision={1}
                            suffix="%"
                            valueStyle={{
                                color: (report.memoryUsage?.usedPercent || 0) > 80 ? '#ff4d4f' : '#52c41a'
                            }}
                        />
                    </Card>
                </Col>
                <Col span={8}>
                    <Card>
                        <Statistic
                            title="网络请求"
                            value={report.networkStats.totalRequests}
                            suffix="个"
                        />
                        <div style={{ fontSize: 12, color: '#666', marginTop: 4 }}>
                            失败: {report.networkStats.failedRequests}个
                        </div>
                    </Card>
                </Col>
            </Row>

            {report.recommendations.length > 0 && (
                <Alert
                    message="性能建议"
                    description={
                        <ul style={{ margin: 0, paddingLeft: 20 }}>
                            {report.recommendations.slice(0, 3).map((rec, index) => (
                                <li key={index}>{rec}</li>
                            ))}
                        </ul>
                    }
                    type="warning"
                    icon={<WarningOutlined />}
                />
            )}
        </div>
    )
}

// 性能指标标签页
function MetricsTab({
    report,
    getTrend
}: {
    report: PerformanceReport | null
    getTrend: (metric: string, timeRange?: number) => TrendData
}) {
    if (!report) {
        return <Alert message="暂无性能数据" type="info" />
    }

    const metrics = [
        { key: 'LCP', name: 'Largest Contentful Paint', unit: 'ms', threshold: 2500 },
        { key: 'FID', name: 'First Input Delay', unit: 'ms', threshold: 100 },
        { key: 'CLS', name: 'Cumulative Layout Shift', unit: '', threshold: 0.1 },
    ]

    const getTrendIcon = (trend: TrendData) => {
        switch (trend.trend) {
            case 'improving':
                return <ArrowDownOutlined style={{ color: '#52c41a' }} />
            case 'degrading':
                return <ArrowUpOutlined style={{ color: '#ff4d4f' }} />
            default:
                return <MinusOutlined style={{ color: '#666' }} />
        }
    }

    const columns = [
        {
            title: '指标',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '当前值',
            key: 'current',
            render: (_: any, record: any) => {
                const metricData = report.metrics[record.key]
                if (!metricData) return '-'

                const value = metricData.avg
                const isGood = value <= record.threshold

                return (
                    <span style={{ color: isGood ? '#52c41a' : '#ff4d4f' }}>
                        {value.toFixed(2)} {record.unit}
                        {isGood ? <CheckCircleOutlined style={{ marginLeft: 4 }} /> : <WarningOutlined style={{ marginLeft: 4 }} />}
                    </span>
                )
            }
        },
        {
            title: '趋势',
            key: 'trend',
            render: (_: any, record: any) => {
                const trend = getTrend(record.key)
                return (
                    <span>
                        {getTrendIcon(trend)}
                        <span style={{ marginLeft: 4 }}>
                            {Math.abs(trend.change).toFixed(1)}%
                        </span>
                    </span>
                )
            }
        },
        {
            title: 'P95',
            key: 'p95',
            render: (_: any, record: any) => {
                const metricData = report.metrics[record.key]
                if (!metricData) return '-'
                return `${metricData.p95?.toFixed(2) || '-'} ${record.unit}`
            }
        }
    ]

    return (
        <div>
            <Table
                dataSource={metrics}
                columns={columns}
                pagination={false}
                size="small"
                rowKey="key"
            />

            {report.memoryUsage && (
                <Card title="内存使用详情" style={{ marginTop: 16 }}>
                    <Row gutter={16}>
                        <Col span={8}>
                            <Statistic
                                title="已使用"
                                value={report.memoryUsage.usedJSHeapSize / 1024 / 1024}
                                precision={2}
                                suffix="MB"
                            />
                        </Col>
                        <Col span={8}>
                            <Statistic
                                title="总计"
                                value={report.memoryUsage.totalJSHeapSize / 1024 / 1024}
                                precision={2}
                                suffix="MB"
                            />
                        </Col>
                        <Col span={8}>
                            <Statistic
                                title="限制"
                                value={report.memoryUsage.jsHeapSizeLimit / 1024 / 1024}
                                precision={2}
                                suffix="MB"
                            />
                        </Col>
                    </Row>
                </Card>
            )}
        </div>
    )
}

// 缓存状态标签页
function CacheTab({ getCacheStats }: { getCacheStats: () => Record<string, any> }) {
    const [cacheStats, setCacheStats] = useState<Record<string, any>>({})

    useEffect(() => {
        const updateStats = () => {
            setCacheStats(getCacheStats())
        }

        updateStats()
        const interval = setInterval(updateStats, 5000)

        return () => clearInterval(interval)
    }, [getCacheStats])

    const cacheTypes = Object.keys(cacheStats)

    if (cacheTypes.length === 0) {
        return <Alert message="暂无缓存数据" type="info" />
    }

    return (
        <div>
            <Row gutter={16}>
                {cacheTypes.map(type => {
                    const stats = cacheStats[type]
                    const hitRate = stats.hitRate || 0

                    return (
                        <Col span={12} key={type} style={{ marginBottom: 16 }}>
                            <Card title={`${type} 缓存`} size="small">
                                <div style={{ marginBottom: 8 }}>
                                    <Progress
                                        percent={hitRate}
                                        format={percent => `命中率 ${percent}%`}
                                        status={hitRate > 80 ? 'success' : hitRate > 60 ? 'normal' : 'exception'}
                                    />
                                </div>
                                <Row gutter={8}>
                                    <Col span={12}>
                                        <Statistic
                                            title="有效项"
                                            value={stats.validItems}
                                        />
                                    </Col>
                                    <Col span={12}>
                                        <Statistic
                                            title="总项数"
                                            value={stats.totalItems}
                                        />
                                    </Col>
                                </Row>
                            </Card>
                        </Col>
                    )
                })}
            </Row>
        </div>
    )
}

// 建议标签页
function RecommendationsTab({ report }: { report: PerformanceReport | null }) {
    if (!report || report.recommendations.length === 0) {
        return (
            <Alert
                message="性能良好"
                description="当前没有性能优化建议"
                type="success"
                icon={<CheckCircleOutlined />}
            />
        )
    }

    const recommendationDetails = {
        'LCP过高，建议优化图片加载和关键资源': {
            priority: 'high',
            actions: [
                '使用 WebP 格式图片',
                '启用图片懒加载',
                '优化关键CSS',
                '使用CDN加速资源加载'
            ]
        },
        'FID过高，建议减少主线程阻塞时间': {
            priority: 'high',
            actions: [
                '拆分长任务',
                '使用 Web Workers',
                '延迟非关键JavaScript',
                '优化第三方脚本'
            ]
        },
        'CLS过高，建议为图片和动态内容设置尺寸': {
            priority: 'medium',
            actions: [
                '为图片设置明确的宽高',
                '为动态内容预留空间',
                '避免在现有内容上方插入内容',
                '使用 CSS aspect-ratio'
            ]
        },
        '内存使用率过高，建议清理未使用的数据和组件': {
            priority: 'medium',
            actions: [
                '清理未使用的事件监听器',
                '及时销毁组件引用',
                '优化图片缓存策略',
                '使用虚拟滚动'
            ]
        },
        'API响应时间过长，建议启用缓存或优化请求': {
            priority: 'low',
            actions: [
                '启用API响应缓存',
                '使用请求去重',
                '优化数据库查询',
                '使用分页加载'
            ]
        }
    }

    return (
        <div>
            {report.recommendations.map((rec, index) => {
                const details = recommendationDetails[rec as keyof typeof recommendationDetails]
                const priorityColor = {
                    high: '#ff4d4f',
                    medium: '#faad14',
                    low: '#52c41a'
                }

                return (
                    <Card
                        key={index}
                        size="small"
                        style={{ marginBottom: 12 }}
                        title={
                            <span>
                                <WarningOutlined style={{ color: priorityColor[details?.priority as keyof typeof priorityColor || 'low'], marginRight: 8 }} />
                                {rec}
                            </span>
                        }
                    >
                        {details && (
                            <div>
                                <div style={{ marginBottom: 8, fontSize: 12, color: '#666' }}>
                                    优先级: <span style={{ color: priorityColor[details.priority as keyof typeof priorityColor] }}>
                                        {details.priority === 'high' ? '高' : details.priority === 'medium' ? '中' : '低'}
                                    </span>
                                </div>
                                <div>
                                    <strong>建议操作:</strong>
                                    <ul style={{ margin: '4px 0 0 0', paddingLeft: 20 }}>
                                        {details.actions.map((action, actionIndex) => (
                                            <li key={actionIndex} style={{ fontSize: 12 }}>{action}</li>
                                        ))}
                                    </ul>
                                </div>
                            </div>
                        )}
                    </Card>
                )
            })}
        </div>
    )
}